package com.lanjiu.lib.communication.timer;

import com.lanjiu.pro.business.BusinessProtocolMessageStandard;
import com.lanjiu.lib.communication.IMSConfig;
import com.lanjiu.lib.communication.interf.IMSClientInterface;
import com.lanjiu.lib.utils.log.Logger;

import java.util.Timer;
import java.util.TimerTask;

/**
 * @description: 消息发送超时定时器，每一条消息对应一个定时器
 * @author: Panwei
 * @date: 2019/10/28 14:30
 */
public class MsgTimeoutTimer extends Timer {

    private IMSClientInterface mImsClient;  //ims客户端
    private BusinessProtocolMessageStandard.CheckUnifiedEntranceMessage mMsg; // 发送的消息
    private int mCurrentResendCount;    //当前重发次数
    private MsgTimeoutTask mTask;
    private int mResendCount = -1;

    public MsgTimeoutTimer(IMSClientInterface imsClient, BusinessProtocolMessageStandard.CheckUnifiedEntranceMessage msg) {
        this.mImsClient = imsClient;
        this.mMsg = msg;
        this.mTask = new MsgTimeoutTask();
        this.schedule(mTask, mImsClient.getResendInterval(), mImsClient.getResendInterval());
        mResendCount = mImsClient.getResendCount();
    }

    public MsgTimeoutTimer(IMSClientInterface imsClient, BusinessProtocolMessageStandard.CheckUnifiedEntranceMessage msg, int resendCount) {
        this.mImsClient = imsClient;
        this.mMsg = msg;
        this.mTask = new MsgTimeoutTask();
        this.schedule(mTask, mImsClient.getResendInterval(), mImsClient.getResendInterval());
        mResendCount = resendCount;
    }

    private class MsgTimeoutTask extends TimerTask {

        @Override
        public void run() {
            if (mImsClient.isClosed()) {
                mImsClient.getMsgDispatcher().dispatchFailureMsg(mMsg, IMSConfig.MSG_CONTENT_TYPE_MESSAGE_SEND_FAIL);
                // 如果客户端关闭则从消息重发管理器删除，通过MSG_ID
                if (mImsClient.getMsgTimeoutTimerManager() != null)
                    mImsClient.getMsgTimeoutTimerManager().remove(mMsg.getUnifiedEntranceMessage().getHead().getUniqueIdentify());  //imsClient.getMsgTimeoutTimerManager().remove(msg.getHead().getMsgId())
                return;
            }
            if (!mImsClient.isNetworkAvailable()) {
                mImsClient.getMsgDispatcher().dispatchFailureMsg(mMsg, IMSConfig.MSG_CONTENT_TYPE_MESSAGE_NETWORK_FAIL);
                // 如果客户端关闭则从消息重发管理器删除，通过MSG_ID
                if (mImsClient.getMsgTimeoutTimerManager() != null)
                    mImsClient.getMsgTimeoutTimerManager().remove(mMsg.getUnifiedEntranceMessage().getHead().getUniqueIdentify());  //imsClient.getMsgTimeoutTimerManager().remove(msg.getHead().getMsgId())
                return;
            }
            mCurrentResendCount++;
            if (mCurrentResendCount > mResendCount) {
                // 重发次数大于可重发次数，直接标识为发送失败，并通过消息转发器通知应用层
                try {
                    // 通知应用层消息发送失败
                    mImsClient.getMsgDispatcher().dispatchFailureMsg(mMsg, IMSConfig.MSG_CONTENT_TYPE_MESSAGE_SEND_TIMEOUT);
                    if (mImsClient.getMsgTimeoutTimerManager() != null)
                        mImsClient.getMsgTimeoutTimerManager().remove(mMsg.getUnifiedEntranceMessage().getHead().getUniqueIdentify());
                } finally {
                    // 从消息发送超时管理器移除该消息
                    if (mImsClient.getMsgTimeoutTimerManager() != null)
                        mImsClient.getMsgTimeoutTimerManager().remove(mMsg.getUnifiedEntranceMessage().getHead().getUniqueIdentify());
                    // 执行到这里，认为连接已断开或不稳定，触发重连
//                    mImsClient.resetConnect();
                    mCurrentResendCount = 0;
                }
            } else {
                // 发送消息，但不再加入超时管理器，达到最大发送失败次数就算了
                send();
            }
        }
    }

    public void send() {
        Logger.print("正在重发消息，message=" + mMsg);
        mImsClient.sendMsg(mMsg, false);
    }

    public Object msg() {
        return mMsg;
    }

    @Override
    public void cancel() {
        if (mTask != null) {
            mTask.cancel();
            mTask = null;
        }
        super.cancel();
    }
}
